//
//  SunFourthVC.m
//  Xspcf
//
//  Created by sunshine on 16/10/11.
//  Copyright © 2016年 小小算盘. All rights reserved.
//

#import "SunFourthVC.h"
#import "SunActivityVC.h"
#import "SunWebVC.h"
#import "SunDelegateWebVC.h"
#import "MJRefresh.h"
#import <UMSocialCore/UMSocialCore.h>
#import "WXApi.h"
#import <StoreKit/StoreKit.h>

#undef Y
#define Y(y) AY(y)

@interface SunFourthVC ()<UITableViewDelegate,UITableViewDataSource,BackButtonHandlerProtocol,WXApiDelegate,SKStoreProductViewControllerDelegate>
{
    NSArray *_optData;
    NSMutableArray *_bannerData;
    UITableView *_tb;
    NSMutableArray *_dataArr;
}
@property (nonatomic, strong) UIButton *onActivity;
@property (nonatomic, strong) UIButton *outButton;
@property (nonatomic, strong) UILabel *redLine;
@property (nonatomic, assign) BOOL isOn;
@property (nonatomic, strong) NSMutableArray *arrarOn;
@property (nonatomic, strong) NSMutableArray *arrarOut;

@end

@implementation SunFourthVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发现";
    self.view.backgroundColor = BACKGROUND;
    [self initData];
    [self creatUI];
    self.isOn = YES;
    // Do any additional setup after loading the view.
}

- (void)initData{
    _optData = [NSArray array];
    _bannerData = [NSMutableArray array];
}
- (void)viewWillAppear:(BOOL)animated {
    [self requestToActivity];
    [self onAction];
}
- (void)creatUI{
//    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 240)];
//    [self.view addSubview:headView];
//    UIView *center = [[UIView alloc]init];
//    [headView addSubview:center];
//    [center lt_Top:SunEdgesMake(0, 0, 0, 104) to:nil save:YES];
//    center.backgroundColor = WHITE;
//
//    UIButton *invBtn = [self btnWithImg:[UIImage imageNamed:@"fourth_invite"] Title:@"邀请好友"];
//    [center addSubview:invBtn];
//    [invBtn addTarget:self action:@selector(gotoInvteFriend) forControlEvents:UIControlEventTouchUpInside];
//    [invBtn lt_setTop:0 to:nil Bottom:0 to:nil save:YES];
//
//    UIButton *askBtn = [self btnWithImg:[UIImage imageNamed:@"fourth_ques"] Title:@"常见问题"];
//    [center addSubview:askBtn];
//    [askBtn addTarget:self action:@selector(gotoAsking) forControlEvents:UIControlEventTouchUpInside];
//    [askBtn lt_setTop:0 to:nil Bottom:0 to:nil save:YES];
//
//    UIButton *actBtn = [self btnWithImg:[UIImage imageNamed:@"fourth_safe"] Title:@"安全保障"];
//    [center addSubview:actBtn];
//    [actBtn addTarget:self action:@selector(gotoActivity) forControlEvents:UIControlEventTouchUpInside];
//    [actBtn lt_setTop:0 to:nil Bottom:0 to:nil save:YES];
//
//    UIButton *comBtn = [self btnWithImg:[UIImage imageNamed:@"fourth_desc"] Title:@"公司简介"];
//    [center addSubview:comBtn];
//    [comBtn addTarget:self action:@selector(gotoDesc) forControlEvents:UIControlEventTouchUpInside];
//    [comBtn lt_setTop:0 to:nil Bottom:0 to:nil save:YES];
//
//    NSArray *cons = [NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[v1]-0-[v2(==v1)]-0-[v3(==v1)]-0-[v4(==v1)]-0-|" options:0 metrics:nil views:@{@"v1":invBtn,@"v2":askBtn,@"v3":actBtn,@"v4":comBtn}];
//    [center addConstraints:cons];
    
    UIView *activityView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 45)];
    [self.view addSubview:activityView];
    [activityView setBackgroundColor:WHITE];
    self.onActivity = [[UIButton alloc]initWithFrame:CGRectMake(0, 5, SCREENWIDTH/2-1, 40)];
    self.onActivity.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:14];
    [self.onActivity setTitle:@"热门活动" forState:UIControlStateNormal];
    self.onActivity.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.onActivity setTitleColor:COLOR_TITLE_MAIN forState:UIControlStateNormal];
    [self.onActivity setTitleColor:COLOR_MAIN forState:UIControlStateSelected];
    [activityView addSubview:self.onActivity];
    [self.onActivity addTarget:self action:@selector(onAction) forControlEvents:UIControlEventTouchUpInside];
    self.onActivity.selected = YES;
    
    self.outButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREENWIDTH/2, 5, SCREENWIDTH/2-1, 40)];
    self.outButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:14];
    [self.outButton setTitle:@"往期活动" forState:UIControlStateNormal];
    self.outButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.outButton setTitleColor:COLOR_TITLE_MAIN forState:UIControlStateNormal];
    [self.outButton setTitleColor:COLOR_MAIN forState:UIControlStateSelected];
    [activityView addSubview:self.outButton];
    [self.outButton addTarget:self action:@selector(outAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.redLine = [[UILabel alloc]init];
    [self.redLine setFrame:CGRectMake((SCREENWIDTH/2-X(45))/2, 43, X(45), 3)];
    self.redLine.backgroundColor = COLOR_MAIN;
    [self.view addSubview:self.redLine];
    
    _tb = [[UITableView alloc]initWithFrame:CGRectMake(X(15), 45, SCREENWIDTH - X(30), SCREENHEIGHT - 141- 20) style:UITableViewStylePlain];
    [self.view addSubview:_tb];
    _tb.delegate = self;
    _tb.dataSource = self;
    _tb.backgroundColor = BACKGROUND;
    _tb.showsVerticalScrollIndicator = NO;
    _tb.separatorStyle = UITableViewCellEditingStyleNone;

}
- (void)onAction{
    self.onActivity.selected = YES;
    self.outButton.selected = NO;
    [self.redLine setFrame:CGRectMake((SCREENWIDTH/2-X(45))/2, 43, X(45), 2)];
    self.isOn = YES;
    _dataArr = self.arrarOn;
    [_tb reloadData];
}
- (void)outAction{
    self.onActivity.selected = NO;
    self.outButton.selected = YES;
    [self.redLine setFrame:CGRectMake(SCREENWIDTH/2+(SCREENWIDTH/2-X(45))/2, 43, X(45), 2)];
    self.isOn = NO;
    _dataArr = self.arrarOut;
    [_tb reloadData];
}
- (UIButton *)btnWithImg:(UIImage *)img Title:(NSString *)title{
    UIButton *btn = [[UIButton alloc]init];
    [btn setImage:img forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:BLACK forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    [btn verticalImageAndTitle:0];
    return btn;
}

#pragma mark button
- (void)gotoActivity{
    SunWebVC *vc = [[SunWebVC alloc]init];
    vc.urlStr = [NSString stringWithFormat:@"%@/guide_about.html?source=ios",KWAP];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)gotoDesc {
    SunWebVC *vc = [[SunWebVC alloc]init];
    vc.urlStr = [NSString stringWithFormat:@"%@/More/getArticleByNid?nid=about&type=2&source=ios",KWAP];
    vc.titleName = @"公司简介";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)share:(UIButton *)btn{
    [[Sun shareSun]hideShow];
    UMSocialPlatformType type;
    switch (btn.tag) {
        case 1:
            type = UMSocialPlatformType_WechatTimeLine;
            break;
        case 2:
            type = UMSocialPlatformType_WechatSession;
            break;
        case 3:
            type = UMSocialPlatformType_QQ;
            break;
        case 4:
            type = UMSocialPlatformType_Sina;
            break;
            
        default:
            break;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_NORMALSHARE];
    [HttpRequest postURL:url withParam:nil success:^(id requestDic, NSString *msg) {
        NSString *img = [requestDic objectForKey:@"img"];
        if (![img containsString:@"http"]) {
            img = [KIMG stringByAppendingString:img];
        }
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[requestDic objectForKey:@"title"] descr:[requestDic objectForKey:@"content"] thumImage:img];
        shareObject.webpageUrl =[requestDic objectForKey:@"url"];
        messageObject.shareObject = shareObject;
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        }];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]showMsg:errorInfo];
    }];
}

- (void)hide{
    [[Sun shareSun]hideShow];
}

- (void)gotoInvteFriend{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = WHITE;
    NSArray *arr = @[@{@"img":@"share_line",@"title":@"朋友圈"},@{@"img":@"share_friend",@"title":@"微信好友"},@{@"img":@"share_qq",@"title":@"QQ好友"},@{@"img":@"share_sina",@"title":@"新浪微博"}];
    for (int i=0; i<4; i++) {
        UIButton *btn = [[UIButton alloc]init];
        [view addSubview:btn];
        [btn lt_setWidth:SCREENWIDTH / 4 save:YES];
        [btn lt_setHeight:Y(82) save:YES];
        [btn lt_setTop:0 to:nil save:YES];
        [btn lt_setLeft:SCREENWIDTH / 4 * i to:nil save:YES];
        btn.tag = i + 1;
        [btn setImage:[UIImage imageNamed:[arr[i] objectForKey:@"img"]] forState:UIControlStateNormal];
        [btn setTitle:[arr[i] objectForKey:@"title"] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn setTitleColor:BLACK forState:UIControlStateNormal];
        [btn verticalImageAndTitle:40];
        [btn addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    }
    UIButton *btn = [[UIButton alloc]init];
    [view addSubview:btn];
    [btn lt_Top:SunEdgesMake(Y(86), X(15), X(15), Y(44)) to:nil save:YES];
    btn.clipsToBounds = YES;
    [btn setBackgroundColor:BLUE forState:UIControlStateNormal];
    [btn setBackgroundColor:[HXColor colorWithHexString:@"87CEFA"] forState:UIControlStateHighlighted];
    btn.layer.cornerRadius = 4;
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:WHITE forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:17];
    [btn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [[Sun shareSun]show:view to:[UIApplication sharedApplication].keyWindow shouldReturn:NO];
    [view lt_Bottom:SunEdgesMake(0, 0, 0, Y(144)) to:nil save:YES];
}

- (void)gotoAsking{
    SunWebVC *vc = [[SunWebVC alloc]init];
    vc.urlStr = [NSString stringWithFormat:@"%@/guide_help.html?nid=help_about&source=ios",KWAP];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)evaluate{
    
    //初始化控制器
    SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
    //设置代理请求为当前控制器本身
    storeProductViewContorller.delegate = self;
    //加载一个新的视图展示
    [storeProductViewContorller loadProductWithParameters:
     //appId唯一的
     @{SKStoreProductParameterITunesItemIdentifier : @"966769021"} completionBlock:^(BOOL result, NSError *error) {
         //block回调
         if(error){
             NSLog(@"error %@ with userInfo %@",error,[error userInfo]);
         }else{
             //模态弹出appstore
             [self presentViewController:storeProductViewContorller animated:YES completion:^{
                 
             }
              ];
         }
     }];
}

//取消按钮监听
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc] init];
    view.backgroundColor = BACKGROUND;
    return view;
}

- (void)requestToActivity{
    [[Sun shareSun]showActivity:self];
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_ACTIVITY];
    [HttpRequest postURL:url withParam:nil success:^(id requestDic, NSString *msg) {
        [[Sun shareSun] hideAll];
        self.arrarOn = [NSMutableArray array];
        self.arrarOut = [NSMutableArray array];
        _dataArr = requestDic;
        for (NSDictionary *activity in _dataArr) {
            if ([[activity objectForKey:@"status"] isEqualToString:@"进行中"]) {
                [self.arrarOn addObject:activity];
            }else{
                [self.arrarOut addObject:activity];
            }
        }
        _dataArr = self.arrarOn;
        [_tb reloadData];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun] hideAll];
        [[Sun shareSun]showMsg:errorInfo];
    }];
}


#pragma mark request
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 198;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    for (int i=0; i<cell.subviews.count; i++) {
        UIView *view = [cell subviews][i];
        [view removeFromSuperview];
        i--;
    }
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = LINE.CGColor;
    cell.clipsToBounds = YES;
    cell.layer.cornerRadius = 10;
    UIImageView *img = [[UIImageView alloc]init];
    [cell addSubview:img];
    [img lt_Top:SunEdgesMake(0, 0, 0, 165) to:nil save:YES];
    [img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KIMG,[_dataArr[indexPath.section] objectForKey:@"img"]]]];
    img.contentMode = UIViewContentModeRedraw;
    
    if (!self.isOn) {
        UIView *overView = [[UIView alloc]init];
        [overView setFrame:CGRectMake(0, 0, cell.frame.size.width+200, 165)];
        [overView setBackgroundColor:[UIColor colorWithRed:0/255 green:0/255 blue:0/255 alpha:0.61]];
        [img addSubview:overView];
        overView.hidden = self.isOn;
        UILabel *overLabel = [[UILabel alloc]initWithFrame:CGRectMake(X(121), 55, 118, 32)];
        [overView addSubview:overLabel];
        overLabel.text = @"活动已结束";
        overLabel.textColor = WHITE;
        overLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20];
        overLabel.textAlignment = NSTextAlignmentCenter;
        overLabel.layer.cornerRadius = 5;
        overLabel.layer.masksToBounds = YES;
        overLabel.layer.borderColor = [UIColor colorWithRed:255/255 green:255/255 blue:255/255 alpha:0.67].CGColor;
        overLabel.layer.borderWidth = 1;
    }
    UILabel *label = [[UILabel alloc]init];
    [cell addSubview:label];
    [label lt_setBottom:8 to:nil save:YES];
    [label lt_setLeft:X(15) to:nil save:YES];
    label.font = [UIFont systemFontOfSize:14];
    [label setMarkup:[NSString stringWithFormat:@"<font color=\"#4A4A4A\">%@</font>",[_dataArr[indexPath.section] objectForKey:@"name"]]];
    UILabel *timeLabel = [[UILabel alloc]init];
    [cell addSubview:timeLabel];
    [timeLabel lt_setBottom:12 to:nil save:YES];
    [timeLabel lt_setRight:X(15) to:nil save:YES];
    timeLabel.font = [UIFont systemFontOfSize:10];
    [timeLabel setMarkup:[NSString stringWithFormat:@"<font color=\"#9B9B9B\">%@</font>",[_dataArr[indexPath.section] objectForKey:@"startTime"]]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [SunSupport shouldPushController:_dataArr[indexPath.section]];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
